#' Stacked histograms add error bars, marked by significance
#'
#' @param data a data.frame contain the input data
#' @param  i col index wtich need to test
#' @param errbar add a distinctive label, TRUE or FEASE could be selected
#' @param result output from aovMcomper or KwWlx. You can also import result calculated from other software (a data frame)
#' @examples
#' # data(data_wt)
#' result = MuiKwWlx(data = data_wt,num = c(4,9,8))
#' res <- MuiPlotStackBar(data = data,i = c(4,9,8) ,result = result)
#' # utput result
#' res[[1]]
#' @return list
#' @author Contact: Tao Wen \email{2018203048@@njau.edu.cn} Jun Yuan \email{junyuan@@njau.edu.cn} PengHao Xie \email{2019103106@@njau.edu.cn}
#' @references
#'
#' Yuan J, Zhao J, Wen T, Zhao M, Li R, Goossens P, Huang Q, Bai Y, Vivanco JM, Kowalchuk GA, Berendsen RL, Shen Q
#' Root exudates drive the soil-borne legacy of aboveground pathogen infection
#' Microbiome 2018,DOI: \url{doi: 10.1186/s40168-018-0537-x}
#' @export


MuiPlotStackBar <- function(data = data,i,result = result,errbar = TRUE,...){

  #-- data prepare
  i = c(2,i)

  data <- data[i]
  result$group = row.names(result)
  abc <- reshape2::melt(result, id="group", variable.name="variable", value.name = "abc")

  # data for plot
  df <- reshape2::melt(data, id="group", variable.name="variable", value.name = "Size")

  ## Data statistics mean, standard deviation, standard error
  mean <- stats::aggregate(df$Size, by=list(df$group, df$variable), FUN=mean)
  sd <- stats::aggregate(df$Size, by=list(df$group, df$variable), FUN=sd)
  len <- stats::aggregate(df$Size, by=list(df$group, df$variable), FUN=length)
  df_res <- data.frame(mean, sd=sd$x, len=len$x)
  colnames(df_res) = c("group", "variable", "Mean", "Sd", "Count")
  df_res$Se <- df_res$Sd/sqrt(df_res$Count)
  levels(df_res $variable) = as.character(unique(df_res$variable))

  # Construct error line coordinates--
  # df_res = plyr::ddply(df_res,"group",transform,label_y = cumsum(Mean))
  # Construct distinctive marker positions
  df_res_sub = plyr::ddply(df_res,"group", summarize,label_y = cumsum(Mean),  label_abc = cumsum(Mean) - 0.5*Mean,
                           variable = variable)

  # df_res = cbind(df_res,df_res_sub[-1])





  df_res <- df_res%>% inner_join(df_res_sub )


  # Factor rearrangement
  df_res$variable = factor(df_res$variable,order = F,levels = levels(df_res$variable)[length(levels(df_res$variable)):1])


  #--conbind plot data
    plotdata <- df_res %>%
    dplyr::left_join(abc,by = c("group","variable"))

  plotdata$variable = factor(plotdata$variable,levels =as.character(unique(df_res$variable))[length(levels(df_res$variable)):1])


  ### ggplot ploting
  p <-  ggplot(plotdata , aes(x= group, y=Mean, fill=variable)) +
    geom_bar(stat="identity",color="black", width=.6) +
    geom_text(aes(y = label_abc, label = abc))


  if (errbar == TRUE) {
  p <- p + geom_errorbar(aes(ymin=label_y-Sd, ymax=label_y +Sd), width=.2)
  }
  p
  return(list(p,plotdata))
}

